function genListElem(itemVO, extraStr) {
    var elem = '<li id="' + itemVO.id + '">'
        + '<a href="/show?id=' + itemVO.id + '" class="link">'
        + '<div class="img"><img src="' + itemVO.picAddr + '" alt="' + itemVO.name + '"></div>'
        + '<h3>' + itemVO.name + '</h3>'
        + '<div class="price"><span class="v-unit">¥</span><span class="v-value">'
        + itemVO.price + '</span></div>'
        + extraStr + '</a></li>';
    return elem;
}

function genList(data, userType) {
    var pList = $("#plist");
    switch (userType) {
        case 2:
            for (var i = 0; i < data.length; i++) {
                if(data[i].sellCount > 0) {
                    pList.append(genListElem(data[i], '<span class="had"><b>已售出</b></span>'));
                } else {
                    pList.append(genListElem(data[i], ''));
                }
            }
            break;
        case 1:
            for (var i = 0; i < data.length; i++) {
                if(data[i].count > 0) {
                    pList.append(genListElem(data[i], '<span class="had"><b>已购买</b></span>'));
                } else {
                    pList.append(genListElem(data[i], ''));
                }
            }
            break;
        default:
            for (var i = 0; i < data.length; i++) {
                pList.append(genListElem(data[i], ''));
            }
            break;
    }
}

function allBtnEvent() {
    var pList = $("#plist");
    $.ajax(
        {
            type: 'get',
            url: '/getAllItems.json',
            cache: false,
            dataType: 'json',
            success: function (data) {
                if (data.code === 200) {
                    $("#all-li").attr("class", "z-sel");
                    $("#not-buy-li").attr("class", "");
                    pList.empty();
                    genList(data.data, user_Data.loginType);
                } else {
                    alert("获取内容失败");
                }
            },
            error: function (data) {
                alert("获取内容失败!");
            }
        }
    );
}

function notBuyBtnEvent() {
    var pList = $("#plist");
    $.ajax(
        {
            type: 'get',
            url: '/getNotBuyItems.json',
            cache: false,
            dataType: 'json',
            success: function (data) {
                if (data.code === 200) {
                    $("#all-li").attr("class", "");
                    $("#not-buy-li").attr("class", "z-sel");
                    pList.empty();
                    genList(data.data, user_Data.loginType);
                } else {
                    alert("获取内容失败");
                }
            },
            error: function (data) {
                alert("获取内容失败!");
            }
        }
    );
}

(function () {
    var userType = user_Data.loginType;
    genList(json_Data, userType);
    //为所有内容按钮绑定事件
    $("#all-btn").click(allBtnEvent);
    $("#not-buy-button").click(notBuyBtnEvent);
})();

